<template>
  <div class="certificate-list">
    <a-card title="证书字典管理">
      <template #extra>
        <a-button type="primary" @click="showAddModal">添加证书类型</a-button>
      </template>

      <a-form layout="inline" class="search-form">
        <a-form-item label="类别">
          <a-select v-model:value="searchForm.sort" placeholder="请选择" style="width: 150px" allow-clear>
            <a-select-option value="学习类">学习类</a-select-option>
            <a-select-option value="竞赛类">竞赛类</a-select-option>
            <a-select-option value="证书类">证书类</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="级别">
          <a-select v-model:value="searchForm.ranks" placeholder="请选择" style="width: 150px" allow-clear>
            <a-select-option value="国家级">国家级</a-select-option>
            <a-select-option value="省级">省级</a-select-option>
            <a-select-option value="校级">校级</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item>
          <a-space>
            <a-button type="primary" @click="handleSearch">查询</a-button>
            <a-button @click="handleReset">重置</a-button>
          </a-space>
        </a-form-item>
      </a-form>

      <a-table 
        :columns="columns" 
        :data-source="dataSource" 
        :loading="loading"
        bordered 
        :pagination="pagination"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'grade'">
            <a-tag color="blue">{{ record.grade }}分</a-tag>
          </template>
          <template v-if="column.key === 'action'">
            <a-space>
              <a @click="showEditModal(record)">编辑</a>
              <a style="color: #ff4d4f" @click="handleDelete(record)">删除</a>
            </a-space>
          </template>
        </template>
      </a-table>
    </a-card>

    <!-- 添加/编辑对话框 -->
    <a-modal 
      v-model:open="modalVisible" 
      :title="isEdit ? '编辑证书类型' : '添加证书类型'"
      @ok="handleSubmit"
      @cancel="handleCancel"
      width="600px"
    >
      <a-form
        :model="formData"
        :label-col="{ span: 5 }"
        :wrapper-col="{ span: 18 }"
      >
        <a-form-item label="类别" required>
          <a-select v-model:value="formData.sort" placeholder="请选择类别">
            <a-select-option value="学习类">学习类</a-select-option>
            <a-select-option value="竞赛类">竞赛类</a-select-option>
            <a-select-option value="证书类">证书类</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="证书名称" required>
          <a-input v-model:value="formData.name" placeholder="请输入证书名称" />
        </a-form-item>
        <a-form-item label="级别" required>
          <a-select v-model:value="formData.ranks" placeholder="请选择级别">
            <a-select-option value="国家级">国家级</a-select-option>
            <a-select-option value="省级">省级</a-select-option>
            <a-select-option value="校级">校级</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="等级" required>
          <a-input v-model:value="formData.classes" placeholder="请输入等级（如：一等奖）" />
        </a-form-item>
        <a-form-item label="对应分数" required>
          <a-input-number 
            v-model:value="formData.grade" 
            placeholder="请输入分数" 
            :min="0"
            :max="100"
            style="width: 100%"
          />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { message, Modal } from 'ant-design-vue'
import { certificateAPI } from '@/api/certificate'
import type { Certificate } from '@/api/certificate'

const loading = ref(false)
const dataSource = ref<Certificate[]>([])

const searchForm = reactive({
  sort: undefined as string | undefined,
  ranks: undefined as string | undefined
})

const columns = [
  { title: 'ID', dataIndex: 'id', key: 'id', width: 80 },
  { title: '类别', dataIndex: 'sort', key: 'sort', width: 120 },
  { title: '证书名称', dataIndex: 'name', key: 'name' },
  { title: '级别', dataIndex: 'ranks', key: 'ranks', width: 120 },
  { title: '等级', dataIndex: 'classes', key: 'classes', width: 120 },
  { title: '对应分数', key: 'grade', width: 100 },
  { title: '操作', key: 'action', width: 150 }
]

const pagination = ref({
  total: 0,
  current: 1,
  pageSize: 10,
  showTotal: (total: number) => `共 ${total} 条`,
  onChange: (page: number, pageSize: number) => {
    pagination.value.current = page
    pagination.value.pageSize = pageSize
    loadData()
  }
})

// 加载数据
const loadData = async () => {
  loading.value = true
  try {
    const res = await certificateAPI.getCertificateList({
      page: pagination.value.current,
      page_size: pagination.value.pageSize,
      sort: searchForm.sort,
      ranks: searchForm.ranks
    })
    dataSource.value = res.data.results
    pagination.value.total = res.data.count
  } catch (error: any) {
    message.error('加载数据失败: ' + (error.response?.data?.message || error.message))
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  pagination.value.current = 1
  loadData()
}

// 重置
const handleReset = () => {
  searchForm.sort = undefined
  searchForm.ranks = undefined
  pagination.value.current = 1
  loadData()
}

// 对话框相关
const modalVisible = ref(false)
const isEdit = ref(false)
const editingId = ref<number | null>(null)

const formData = reactive({
  sort: '',
  name: '',
  ranks: '',
  classes: '',
  grade: 0
})

// 显示添加对话框
const showAddModal = () => {
  isEdit.value = false
  editingId.value = null
  formData.sort = ''
  formData.name = ''
  formData.ranks = ''
  formData.classes = ''
  formData.grade = 0
  modalVisible.value = true
}

// 显示编辑对话框
const showEditModal = (record: Certificate) => {
  isEdit.value = true
  editingId.value = record.id
  formData.sort = record.sort
  formData.name = record.name
  formData.ranks = record.ranks
  formData.classes = record.classes
  formData.grade = record.grade
  modalVisible.value = true
}

// 取消对话框
const handleCancel = () => {
  modalVisible.value = false
}

// 提交表单
const handleSubmit = async () => {
  if (!formData.sort || !formData.name || !formData.ranks || !formData.classes || !formData.grade) {
    message.warning('请填写完整信息')
    return
  }

  try {
    if (isEdit.value && editingId.value) {
      await certificateAPI.updateCertificate(editingId.value, formData)
      message.success('更新成功')
    } else {
      await certificateAPI.createCertificate(formData)
      message.success('添加成功')
    }
    modalVisible.value = false
    loadData()
  } catch (error: any) {
    message.error(error.response?.data?.message || '操作失败')
  }
}

// 删除证书
const handleDelete = (record: Certificate) => {
  Modal.confirm({
    title: '确认删除',
    content: `确定要删除证书"${record.name}"吗？`,
    okText: '确定',
    cancelText: '取消',
    onOk: async () => {
      try {
        await certificateAPI.deleteCertificate(record.id)
        message.success('删除成功')
        loadData()
      } catch (error: any) {
        message.error(error.response?.data?.message || '删除失败')
      }
    }
  })
}



onMounted(() => {
  loadData()
})
</script>

<style scoped>
.search-form {
  margin-bottom: 20px;
}
</style>
